{% extends "base.html" %}

{% block title %}仪表板 - 个人数据分析仪表板{% endblock %}

{% block content %}
<div class="row">
    <!-- 主要内容区域 -->
    <div class="col-lg-9">
        <!-- 数据概览 -->
        <div class="card mb-4 fade-in">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>
                    数据概览
                </h5>
                <span class="badge bg-light text-dark">
                    {{ data_info.filename }}
                </span>
            </div>
            <div class="card-body">
                <div class="stats-grid" id="statsGrid">
                    <!-- 动态加载统计卡片 -->
                </div>
                
                <!-- 数据预览表格 -->
                <div class="mt-4">
                    <h6 class="mb-3">
                        <i class="fas fa-table me-2"></i>
                        数据预览
                    </h6>
                    <div class="table-responsive">
                        <div id="dataPreview">
                            <!-- 动态加载数据表格 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表生成区域 -->
        <div class="card mb-4 fade-in">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">
                    <i class="fas fa-chart-bar me-2"></i>
                    可视化分析
                </h5>
            </div>
            <div class="card-body">
                <!-- 图表控制面板 -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <label for="chartType" class="form-label">图表类型</label>
                        <select class="form-select" id="chartType">
                            <option value="">选择图表类型</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="xColumn" class="form-label">X轴 / 主要列</label>
                        <select class="form-select" id="xColumn">
                            <option value="">选择列</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="yColumn" class="form-label">Y轴 / 次要列</label>
                        <select class="form-select" id="yColumn">
                            <option value="">选择列（可选）</option>
                        </select>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button class="btn btn-primary w-100" id="generateChart" disabled>
                            <i class="fas fa-magic me-2"></i>
                            生成图表
                        </button>
                    </div>
                </div>
                
                <!-- 图表显示区域 -->
                <div class="chart-container" id="chartContainer" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0">
                            <i class="fas fa-chart-line me-2"></i>
                            图表结果
                        </h6>
                        <button class="btn btn-outline-primary btn-sm" id="exportChart" disabled>
                            <i class="fas fa-download me-1"></i>
                            导出图表
                        </button>
                    </div>
                    <div id="chartImage" class="text-center">
                        <!-- 图表将在这里显示 -->
                    </div>
                </div>
                
                <!-- 图表生成进度 -->
                <div class="text-center" id="chartLoading" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">生成中...</span>
                    </div>
                    <p class="mt-2 mb-0">正在生成图表，请稍候...</p>
                </div>
            </div>
        </div>

        <!-- 智能推荐 -->
        <div class="card mb-4 fade-in">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0">
                    <i class="fas fa-lightbulb me-2"></i>
                    智能图表推荐
                </h5>
            </div>
            <div class="card-body">
                <div id="chartRecommendations">
                    <!-- 动态加载推荐卡片 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 侧边栏 -->
    <div class="col-lg-3">
        <div class="sidebar fade-in">
            <!-- 文件信息 -->
            <div class="mb-4">
                <h6 class="text-primary mb-3">
                    <i class="fas fa-file-alt me-2"></i>
                    文件信息
                </h6>
                <div class="small">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">文件名:</span>
                        <span class="fw-bold">{{ data_info.filename or '未知' }}</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">上传时间:</span>
                        <span id="uploadTime">-</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">数据行数:</span>
                        <span id="totalRows">-</span>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">数据列数:</span>
                        <span id="totalCols">-</span>
                    </div>
                </div>
            </div>

            <!-- 数据质量 -->
            <div class="mb-4">
                <h6 class="text-warning mb-3">
                    <i class="fas fa-shield-alt me-2"></i>
                    数据质量
                </h6>
                <div id="dataQuality">
                    <!-- 动态加载数据质量信息 -->
                </div>
            </div>

            <!-- 统计摘要 -->
            <div class="mb-4">
                <h6 class="text-success mb-3">
                    <i class="fas fa-calculator me-2"></i>
                    统计摘要
                </h6>
                <div id="statisticsSummary">
                    <!-- 动态加载统计信息 -->
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="d-grid gap-2">
                <button class="btn btn-outline-primary btn-sm" onclick="location.href='/'">
                    <i class="fas fa-upload me-2"></i>
                    上传新文件
                </button>
                <button class="btn btn-outline-success btn-sm" id="refreshData">
                    <i class="fas fa-sync-alt me-2"></i>
                    刷新数据
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}{% endblock %}
<script>
let currentData = null;
let currentChart = null;

$(document).ready(function() {
    // 加载数据信息
    loadDataInfo();
    
    // 绑定事件
    $('#chartType').change(updateColumnOptions);
    $('#generateChart').click(generateChart);
    $('#exportChart').click(exportChart);
    $('#refreshData').click(loadDataInfo);
    
    // 检查图表生成按钮状态
    $('#chartType, #xColumn').change(checkGenerateButton);
});

function loadDataInfo() {
    $.ajax({
        url: '/api/data-info',
        type: 'GET',
        success: function(response) {
            currentData = response;
            updateUI(response);
        },
        error: function(xhr, status, error) {
            showAlert('error', '加载数据失败，请刷新页面重试');
        }
    });
}

function updateUI(data) {
    // 更新基本信息
    updateBasicInfo(data.data_info);
    
    // 更新统计卡片
    updateStatsGrid(data.analysis);
    
    // 更新数据预览
    $('#dataPreview').html(data.preview);
    
    // 更新侧边栏
    updateSidebar(data.analysis);
    
    // 更新图表推荐
    updateChartRecommendations(data.analysis.chart_recommendations);
    
    // 更新列选择器
    updateColumnSelectors(data.analysis.column_types);
}

function updateBasicInfo(dataInfo) {
    $('#uploadTime').text(formatDateTime(dataInfo.upload_time));
    $('#totalRows').text(dataInfo.total_rows.toLocaleString());
    $('#totalCols').text(dataInfo.total_cols);
}

function updateStatsGrid(analysis) {
    const basicInfo = analysis.basic_info;
    const missingValues = analysis.missing_values;
    const columnTypes = analysis.column_types;
    
    const statsHtml = `
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-muted mb-1">总行数</h6>
                    <h4 class="mb-0 text-primary">${basicInfo.rows.toLocaleString()}</h4>
                </div>
                <i class="fas fa-list fa-2x text-primary opacity-50"></i>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-muted mb-1">总列数</h6>
                    <h4 class="mb-0 text-success">${basicInfo.columns}</h4>
                </div>
                <i class="fas fa-columns fa-2x text-success opacity-50"></i>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-muted mb-1">数值列</h6>
                    <h4 class="mb-0 text-info">${columnTypes.numeric.length}</h4>
                </div>
                <i class="fas fa-calculator fa-2x text-info opacity-50"></i>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-muted mb-1">缺失值</h6>
                    <h4 class="mb-0 text-warning">${missingValues.total_missing.toLocaleString()}</h4>
                </div>
                <i class="fas fa-exclamation-triangle fa-2x text-warning opacity-50"></i>
            </div>
        </div>
    `;
    
    $('#statsGrid').html(statsHtml);
}

function updateSidebar(analysis) {
    // 数据质量
    const missingValues = analysis.missing_values;
    const qualityScore = calculateQualityScore(missingValues, analysis.basic_info.rows);
    
    let qualityColor = 'success';
    if (qualityScore < 70) qualityColor = 'danger';
    else if (qualityScore < 85) qualityColor = 'warning';
    
    const qualityHtml = `
        <div class="progress mb-2" style="height: 8px;">
            <div class="progress-bar bg-${qualityColor}" style="width: ${qualityScore}%"></div>
        </div>
        <div class="small text-muted">
            <div class="d-flex justify-content-between">
                <span>质量评分:</span>
                <span class="fw-bold text-${qualityColor}">${qualityScore}%</span>
            </div>
            <div class="d-flex justify-content-between">
                <span>缺失值列:</span>
                <span>${missingValues.columns_with_missing}</span>
            </div>
        </div>
    `;
    
    $('#dataQuality').html(qualityHtml);
    
    // 统计摘要
    const columnTypes = analysis.column_types;
    const summaryHtml = `
        <div class="small">
            <div class="d-flex justify-content-between mb-1">
                <span class="text-muted">数值列:</span>
                <span class="badge bg-primary">${columnTypes.numeric.length}</span>
            </div>
            <div class="d-flex justify-content-between mb-1">
                <span class="text-muted">分类列:</span>
                <span class="badge bg-success">${columnTypes.categorical.length}</span>
            </div>
            <div class="d-flex justify-content-between">
                <span class="text-muted">日期列:</span>
                <span class="badge bg-info">${columnTypes.datetime.length}</span>
            </div>
        </div>
    `;
    
    $('#statisticsSummary').html(summaryHtml);
}

function updateChartRecommendations(recommendations) {
    let recHtml = '';
    
    if (recommendations.length === 0) {
        recHtml = '<p class="text-muted text-center">暂无推荐图表</p>';
    } else {
        recHtml = '<div class="row">';
        recommendations.forEach(rec => {
            recHtml += `
                <div class="col-md-6 mb-3">
                    <div class="card border-primary">
                        <div class="card-body p-3">
                            <h6 class="card-title text-primary mb-2">${rec.name}</h6>
                            <p class="card-text small text-muted mb-2">${rec.description}</p>
                            <div class="small">
                                <strong>适用列:</strong> ${rec.suitable_for.slice